import 'dart:convert';

import 'package:dio/dio.dart' as dio;
import 'package:flutter/material.dart';
import 'package:fluttertoast/fluttertoast.dart';
import 'package:gameplay_flutter/lib_basemodel/discover/address_info_entity.dart';
import 'package:gameplay_flutter/lib_basemodel/discover/moment_entity.dart';
import 'package:gameplay_flutter/lib_basemodel/discover/upload_video_res_entity.dart';
import 'package:gameplay_flutter/lib_baseview/widget/dialogs.dart';
import 'package:gameplay_flutter/lib_im/index.dart';
import 'package:geolocator/geolocator.dart';
import 'package:get/get.dart';
import 'package:image_picker/image_picker.dart';
import 'package:rich_text_controllerx/rich_text_controllerx.dart';
import 'package:wechat_assets_picker/wechat_assets_picker.dart';

import '../../lib_basemodel/discover/discover_topic_entity.dart';
import '../../lib_network/http_api.dart';
import '../../lib_network/http_helper.dart';
import '../../lib_runtime/utils/map_util.dart';
import '../../resource/language/generated/l10n.dart';
import '../sel_friend/sel_friend_view.dart';
import 'model/at_user_model.dart';

class PostLogic extends GetxController {
  var titleController = TextEditingController();
  var contentController = RichTextController(
    text: '',
    onMatch: (match) {},
    targets: [
      MatchTargetItem.regex(
        RegExp(r'(^|\s)(@|#)([\S]+([^\s]))', unicode: true),
        style: const TextStyle(color: Color(0xff8A72FE), fontWeight: FontWeight.bold),
      ),
    ],
  );
  var previewText = "";
  var address = AddressInfoEntity().obs;
  Position? pos;

  var topics = <DiscoverTopicEntity>[].obs;
  var currentTopic = DiscoverTopicEntity().obs;

  //1:仅自己可见 2:个人主页可见 3:所有人可见 4:好友可见
  var permission = 3.obs;
  var topocId = 0.obs;
  var sendEnable = false.obs;

  var atUsers = <FriendModel>[].obs;
  var selectedAssets = <AssetEntity>[].obs;
  var selectedImages = <String>[].obs;

  var files = <UploadVideoResEntity>[].obs;
  var postType = 1;

  getPermissionString() {
    switch (permission()) {
      case 1:
        return T.current.discover5_private_status;
      case 2:
        return T.current.discover5_only_homepage;
      case 3:
        return T.current.discover5_public;
      case 4:
        return T.current.c_friend;
      default:
        return "";
    }
  }

  @override
  void onInit() {
    // fetchNearbyPlaces();
    // discoverRecommendList();

    contentController.addListener(() {
      TextControlUtils.setSpaceTextControl(contentController);
    },);
    super.onInit();
  }

  @override
  void onClose() {
    titleController.dispose();
    contentController.dispose();
    super.onClose();
  }

  uploadVideo() async {
    var asset = selectedAssets.first;
    var file = await asset.file;

    // if (file != null) {
    //   int fileSize = file.lengthSync(); // 同步获取字节大小
    //   double sizeInMB = fileSize / (1024 * 1024); // 转换为 MB
    //   if (sizeInMB > 50) {
    //     showToast(T.current.discover9_file_size);
    //     return;
    //   }
    // }

    var name = DateTime.now().millisecondsSinceEpoch.toString();

    // AssetEntity fileAssetEntity = asset;

    // // if (fileAssetEntity != null) {
    // //   final tmpfiel = await file?.fileAssetEntity;
    // // }

    // Map<String, dynamic>? tmpMap = {
    //   "file": await multipartFileFromAssetEntity(asset),
    //   // 'file': await asset.file?.filePath ?? '',
    // "name": file?.path,
    // "width": asset.width,
    // };

    // var res = await HttpHelper.instance().post(
    //   HttpApi.uploadVideo,
    //   body: tmpMap,
    //   showLoading: true,
    //   showToast: true,
    // );

    // debugPrint("uploadVideo ${res.result}");

    // 获取当前时间
    DateTime now = DateTime.now();

    // 获取当前时间的时间戳（毫秒）
    int timestampInMilliseconds = now.millisecondsSinceEpoch;

    /// file: 0.默认状态 1.图片  2.视频 3-音频 4心情
    /// name: 图片名字（感觉没什么实际作用）
    Map<String, dynamic>? body = {
      "name": file?.path,
      "width": asset.width,
    };
    print("dsafadfadf before $body");

    var response = await HttpHelper.instance().multiUpload(
      HttpApi.uploadVideo,
      body,
      selectedAssets,
    );

    print("dsafadfadf res $response");
    if (response != null) {
      files.assignAll([UploadVideoResEntity.fromJson(response.result)]);
      print("dsafadfadf $files");
    }
  }

  uploadImage() async {
    List<dio.MultipartFile> list = [];

    for (var value in selectedAssets) {
      list.add(await multipartFileFromAssetEntity(value));
    }
    // 获取当前时间
    DateTime now = DateTime.now();

    // 获取当前时间的时间戳（毫秒）
    int timestampInMilliseconds = now.millisecondsSinceEpoch;

    /// file: 0.默认状态 1.图片  2.视频 3-音频 4心情
    /// name: 图片名字（感觉没什么实际作用）
    Map<String, dynamic>? body = {'file': 1, 'name': '${timestampInMilliseconds}.jpg'};

    var response = await HttpHelper.instance().multiUpload(
      HttpApi.discoverUpload,
      body,
      selectedAssets,
    );

    print("dsafadfadf 1111 $response");

    if (response != null) {
      var urls = (response.result as List).cast<String>();

      var tList = <UploadVideoResEntity>[];

      for (var i = 0; i < urls.length; i++) {
        var url = urls[i];
        tList.add(UploadVideoResEntity()
          ..url = url
          ..height = selectedAssets[i].height
          ..width = selectedAssets[i].width);
      }
      ;
      files.assignAll(tList);
      print("dsafadfadf $files");
    }
  }

  Future<dio.MultipartFile> multipartFileFromAssetEntity(AssetEntity entity) async {
    dio.MultipartFile mf;
    // Using the file path.
    final file = await entity.file;
    if (file == null) {
      throw StateError('Unable to obtain file of the entity ${entity.id}.');
    }
    mf = await dio.MultipartFile.fromFile(file.path);
    // Using the bytes.
    final bytes = await entity.originBytes;
    if (bytes == null) {
      throw StateError('Unable to obtain bytes of the entity ${entity.id}.');
    }
    mf = dio.MultipartFile.fromBytes(bytes);
    return mf;
  }

  discoverSaveDynamic() async {
    print(selectedAssets.isEmpty);
    print(!sendEnable());
    if (selectedAssets.isEmpty || !sendEnable()) {
      return;
    }

    var title = titleController.text;
    var contentStr = contentController.text;

    if (title.length > 40) {
      return;
    }

    // topocId(currentTopic().id);

    var contents = json.encode(convertStringToATUserModels(contentStr, atUsers()));

    if (selectedAssets.isNotEmpty) {
      if (selectedAssets.first.type == AssetType.video) {
        var asset = selectedAssets.first;
        var file = await asset.file;

        if (file != null) {
          int fileSize = file.lengthSync(); // 同步获取字节大小
          double sizeInMB = fileSize / (1024 * 1024); // 转换为 MB
          if (sizeInMB > 50) {
            showToast(T.current.discover9_file_size);
            return;
          }
        }
        postType = 2;
        await uploadVideo();
      } else {
        postType = 1;
        await uploadImage();
      }
    }

    if (files.isEmpty) return;

    var res = await HttpHelper.instance().post(
      HttpApi.discoverSaveDynamic,
      body: {
        "type": postType,
        "cityName": getCityName(address()),
        "countryName": getCountryName(address()),
        "countryCode": getCountryCode(address()),
        "contentInfoListStr": contents,
        "lat": pos?.latitude ?? 0,
        "lon": pos?.longitude ?? 0,
        "permission": permission(), //1:仅自己可见 2:个人主页可见 3:所有人可见 4:好友可见
        // if (topocId() != 0) "topicId": topocId(),
        "files": json.encode(files),
        "title": title,
      },
      showLoading: true,
      showToast: true,
    );
    if (res.isSuccess) {
      Get.back(result: res.result["id"]);
      // Get.back(result: true);
    }
  }

  atUser(context) async {
    var user = await Get.to(() => SelFriendPage());
    if (user is FriendModel) {
      atUsers.add(user);
      var mText = contentController.text;
      if (mText.endsWith(' @')) {
        contentController.text = "$mText${user.nickname}  ";
      } else {
        var newText = "$mText @${user.nickname} ";
        contentController.text = "$mText @${user.nickname} ";
      }
    }
  }

  selTopic(DiscoverTopicEntity element) {
    var cText = contentController.text.replaceAll(" #${currentTopic().name} ", "");
    if (currentTopic().name.isNotEmpty) topics.add(currentTopic());
    topics.remove(element);
    currentTopic(element);
    contentController.text = cText;

    Future.delayed(
      60.milliseconds,
      () {
        contentController.text = cText + " #${currentTopic().name} ";
      },
    );
  }

  selAssets() async {
    var res = await AssetPicker.pickAssets(
      Get.context!,
      pickerConfig: AssetPickerConfig(
        selectedAssets: selectedAssets(),
        requestType: RequestType.common,
        specialPickerType: SpecialPickerType.wechatMoment,
      ),
    );
    var list = res ?? [];
    if (list.any((element) => element.type == AssetType.image)) {
      list = list.where((element) => element.type == AssetType.image).toList();
    }

    selectedAssets.assignAll(list);
    sendEnable(selectedAssets.isNotEmpty);
  }

  fetchNearbyPlaces() async {
    debugPrint("fetchNearbyPlaces start}");
    var res = await GoogleMapUtils.fetchNearbyPlaces();
    debugPrint("fetchNearbyPlaces ${res.toString()}");
  }

  addLocation() async {
    var pos = await GoogleMapUtils.getCurrentPosition();
    this.pos = pos;
    var res = await HttpHelper.instance().post(
      HttpApi.geocode,
      body: {"lat": pos?.latitude, "lon": pos?.longitude},
      showLoading: true,
      showToast: true,
    );

    address.value = AddressInfoEntity.fromJson(res.result);
  }

  getCityName(AddressInfoEntity address) {
    return address.results.firstOrNull?.addressComponents
            .firstWhereOrNull((element) => element.types.contains("locality"))
            ?.longName ??
        "";
  }

  getCountryName(AddressInfoEntity address) {
    return address.results.firstOrNull?.addressComponents
            .firstWhereOrNull((element) => element.types.contains("country"))
            ?.longName ??
        "";
  }

  getCountryCode(AddressInfoEntity address) {
    return address.results.firstOrNull?.addressComponents
            .firstWhereOrNull((element) => element.types.contains("country"))
            ?.shortName ??
        "";
  }
}

// uploadVideo() async {
//   var asset = selectedAssets.first;
//
//   var videoFile = await asset.file;
//
//
//   MediaInfo? mediaInfo = await VideoCompress.compressVideo(
//     videoFile!.path,
//     quality: VideoQuality.DefaultQuality,
//     deleteOrigin: false,
//   );
//
//   if (mediaInfo == null) {
//     // isUploading = false;
//     print('转码失败');
//     return;
//   }
//
//   final compressedFile = File(mediaInfo.path!);
//   final fileSize = await compressedFile.length();
//
//   // 检查文件大小是否超过50MB
//   if (fileSize > 50 * 1024 * 1024) {
//     // isUploading = false;
//     print('压缩后的文件大小不能超过50M');
//     return;
//   }
//
//   // 生成文件名
//   final fileName = DateTime.now().millisecondsSinceEpoch.toString();
//
//
//
//
//   var res = await HttpHelper.instance().post(
//     HttpApi.uploadVideo,
//     body: {
//       "file": dio.MultipartFile,
//       "name": fileName,
//       "width": asset.width,
//     },
//     showLoading: true,
//     showToast: true,
//   );
//
//   debugPrint("uploadVideo ${res.result}");
// }

class TextControlUtils{
  //这里面暂时只有一个方法 处理当设置  为  TextAlign.right 活  TextAlign.end 末尾输入空格问题
  static void setSpaceTextControl(TextEditingController textEditingController){
    String oldString = textEditingController.text;
    print(oldString.isNotEmpty);
    if(oldString.lastIndexOf(" ")==oldString.length-1&&oldString.isNotEmpty){
      textEditingController.text = oldString.replaceAll(" ", "\u{00a0}");
      textEditingController.selection = TextSelection.fromPosition(TextPosition(
          affinity: TextAffinity.downstream,
          offset: textEditingController.text.length));
    }
  }
}